package com.udf.hive.udf.number;

import java.util.logging.Logger;

import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.Text;

/**
 * 数字转中文函数
 * 
 * @作者 Administrator
 * @version [版本号, 2019年12月12日]
 */
public class NumberToChineseUDF extends UDF
{

    private static Logger logger = Logger.getLogger("NumberToChineseUDF");

    /**
     * 数据处理逻辑
     * 
     * @param str
     * @return
     */
    public Text evaluate(Text str) {
        if (str == null) {
            return null;
        }
        String value = String.valueOf(str).trim();
        String result = null;
        // 目前只对整型做转换
        try {
            Integer i = Integer.parseInt(value);
            result = int2chineseNum(i);
        }
        catch (Exception e) {
            result = value;
            throw new RuntimeException(e);
        }

        return new Text(result);
    }

    /**
     * 数字转中文 只支持10位
     * 
     * @param src
     * @return
     */
    public String int2chineseNum(int src) {
        final String[] num = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九" };
        final String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };
        StringBuilder dst = new StringBuilder();
        int count = 0;
        while (src > 0) {
            dst.insert(0, (num[src % 10] + unit[count]));
            src = src / 10;
            count++;
        }
        return String.valueOf(dst).replaceAll("零[千百十]", "零").replaceAll("零+万", "万").replaceAll("零+亿", "亿")
                .replaceAll("亿万", "亿零").replaceAll("零+", "零").replaceAll("零$", "");
    }

    public static void main(String[] args) {
        logger.info(String.valueOf(new NumberToChineseUDF().evaluate(new Text("1234567890"))));
    }
}
